package com.jinglvhuanjing.app.widget;

import static com.jinglvhuanjing.app.utils.SingletonSerl.getDjzt;
import static com.jinglvhuanjing.app.utils.SingletonSerl.getTklx;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.jinglvhuanjing.app.R;
import com.jinglvhuanjing.app.bean.LogEvent;
import com.jinglvhuanjing.app.bean.RunEvent;
import com.jinglvhuanjing.app.bean.param.ParamLayout3Bean;
import com.jinglvhuanjing.app.utils.ByteUtil;
import com.jinglvhuanjing.app.utils.LOG;
import com.jinglvhuanjing.app.utils.SerialMsgHandler;
import com.jinglvhuanjing.app.utils.SingletonSerl;
import com.jinglvhuanjing.app.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

public class ParamSettingRow3SecView extends ConstraintLayout {
    public static String TAG = "运行状态";

    public ParamSettingRow3SecView(@NonNull Context context) {
        super(context);
        this.init(context);
    }

    public ParamSettingRow3SecView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.init(context);
    }

    public ParamSettingRow3SecView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.init(context);
    }

    /*** 满溢数值 ***/
    private ParamSettingTermView mysz;
    /*** 满溢限值 ***/
    private ParamSettingTermView myxz;
    /*** 电机电流 ***/
    private ParamSettingTermView djdl;
    /*** 电机限流 ***/
    private ParamSettingTermView djxl;
    /*** 称重数据 ***/
    private ParamSettingTermView czsj;
    /*** 闭门时间 ***/
    private ParamSettingTermView bmsj;
    /*** 满溢状态 ***/
    private ParamSettingTermView myzt;
    /*** 电机状态 ***/
    private ParamSettingTermView djzt;
    /*** 感应信号 ***/
    private ParamSettingTermView gyxh;
    /*** 按钮信号 ***/
    private ParamSettingTermView anxh;
    /*** 投口类型 ***/
    private ParamSettingTermView tklx;

    /*** 投口对应TextView集合 ***/
    private HashMap<String, LinkedList<CustomTextView>> tkViewMap;

    /*** 解析收到的投口信息 ***/
    Handler mHandlerIn = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String obj = (String) msg.obj;
                    LOG.e(TAG, "读取内容1:" + obj);
                    if (!StringUtils.isEmpty(obj)) {
                        byte[] bytes_ = ByteUtil.hexStringToBytes(obj);
                        if (bytes_ != null && bytes_.length > 1) {
                            // 03 功能码，轮询信息返回
                            if (bytes_[1] == SingletonSerl.byte_gnm_type && bytes_.length > 20) {
                                LOG.e(TAG, "读取内容2:" + obj);
                                LOG.e(SerialMsgHandler.TAG, "读取内容:" + obj);
                                if(mysz!=null&&mysz.open(bytes_[0], false)){
                                    parseByte(bytes_);
                                }
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Subscribe
    public void onEvent(RunEvent event) {
        String hex = ByteUtil.hexBytesToString(event.getValue());
        LOG.e(SerialMsgHandler.TAG, TAG+"-读取内容:" + hex);
        LOG.e(TAG, "读取内容5:" + hex);
        Message message = this.mHandlerIn.obtainMessage();
        message.what = 0;
        message.obj = hex;
        this.mHandlerIn.sendMessage(message);
    }

    private void init(Context context) {
        setClipChildren(false);
        LayoutInflater.from(context).inflate(R.layout.view_params_setting_row_3_sec_layout, this, true);
        this.mysz = findViewById(R.id.param_setting_term_mysz);
        this.myxz = findViewById(R.id.param_setting_term_myxz);
        this.djdl = findViewById(R.id.param_setting_term_djdl);
        this.djxl = findViewById(R.id.param_setting_term_djxl);
        this.czsj = findViewById(R.id.param_setting_term_czsj);
        this.czsj = findViewById(R.id.param_setting_term_czsj);
        this.bmsj = findViewById(R.id.param_setting_term_bmsj);
        this.myzt = findViewById(R.id.param_setting_term_myzt);
        this.djzt = findViewById(R.id.param_setting_term_djzt);
        this.gyxh = findViewById(R.id.param_setting_term_gyxh);
        this.anxh = findViewById(R.id.param_setting_term_anxh);
        this.tklx = findViewById(R.id.param_setting_term_tklx);

        this.mysz.setLabel("满溢数值");
        this.myxz.setLabel("满溢限值");
        this.djdl.setLabel("电机电流");
        this.djxl.setLabel("电机限流");
        this.czsj.setLabel("称重数据");
        this.bmsj.setLabel("闭门时间");
        this.myzt.setLabel("满溢状态");
        this.djzt.setLabel("电机状态");
        this.gyxh.setLabel("感应信号");
        this.anxh.setLabel("按钮信号");
        this.tklx.setLabel("投口类型");

        this.mysz.setParamTag("参数设置_满溢数值", ParamLayout3Bean.PARAM_KEY_CSSZ_MYSZ);
        this.myxz.setParamTag("参数设置_满溢限值", ParamLayout3Bean.PARAM_KEY_CSSZ_MYXZ);
        this.djdl.setParamTag("参数设置_电机电流", ParamLayout3Bean.PARAM_KEY_CSSZ_DJDL);
        this.djxl.setParamTag("参数设置_电机限流", ParamLayout3Bean.PARAM_KEY_CSSZ_DJXL);
        this.czsj.setParamTag("参数设置_称重数据", ParamLayout3Bean.PARAM_KEY_CSSZ_CZSJ);
        this.bmsj.setParamTag("参数设置_闭门时间", ParamLayout3Bean.PARAM_KEY_CSSZ_BMSJ);
        this.myzt.setParamTag("参数设置_满溢状态", ParamLayout3Bean.PARAM_KEY_CSSZ_MYZT);
        this.djzt.setParamTag("参数设置_电机状态", ParamLayout3Bean.PARAM_KEY_CSSZ_DJZT);
        this.gyxh.setParamTag("参数设置_感应信号", ParamLayout3Bean.PARAM_KEY_CSSZ_GYXH);
        this.anxh.setParamTag("参数设置_按钮信号", ParamLayout3Bean.PARAM_KEY_CSSZ_ANXH);
        this.tklx.setParamTag("参数设置_投口类型", ParamLayout3Bean.PARAM_KEY_CSSZ_TKLX);

        this.mysz.setTkVisible(true);

        SerialMsgHandler.getInstance().setStartListener(true, this.mHandlerIn);
        EventBus.getDefault().register(this);

//        byte[] bytes1 = ByteUtil.hexStringToBytes("0103000A0008640E010310000100C40064000707D0000013886000DB58");
////        byte[] bytes1 = new byte[]{(byte) 0x01, (byte) 0x03, (byte) 0x10, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0xC4, (byte) 0x00, (byte) 0x64,(byte) 0x00,
////                (byte) 0x06, (byte) 0x07, (byte) 0xD0, (byte) 0x00, (byte) 0x00, (byte) 0x13, (byte) 0x88, (byte) 0x60, (byte) 0x00, (byte) 0xD6, (byte) 0xC8};
//        String b = ByteUtil.hexBytesToString(bytes1);
//        LOG.e(TAG, "b="+b);
//        //将来数据写入主线程
//        Message message = new Message();
//        message.obj = bytes1;
//        message.what = 1;
//        mHandlerIn.sendMessage(message);
    }

    /**
     * 获取值
     *
     * @return 集合
     */
    public ArrayList<HashMap<String, String>> getFormValue() {
        ArrayList<HashMap<String, String>> values = new ArrayList<>();
        values.addAll(this.mysz.getValue());
        values.addAll(this.myxz.getValue());
        values.addAll(this.djdl.getValue());
        values.addAll(this.djxl.getValue());
        values.addAll(this.czsj.getValue());
        values.addAll(this.bmsj.getValue());
        values.addAll(this.myzt.getValue());
        values.addAll(this.djzt.getValue());
        values.addAll(this.gyxh.getValue());
        values.addAll(this.anxh.getValue());
        values.addAll(this.tklx.getValue());
        return values;
    }

    /**
     * 获取TextView集合
     *
     * @return 集合
     */
    public LinkedList<CustomTextView> getCustomTextViewList() {
        LinkedList<CustomTextView> values = new LinkedList<>();
        values.addAll(this.mysz.getView());
        values.addAll(this.myxz.getView());
        values.addAll(this.djdl.getView());
        values.addAll(this.djxl.getView());
        values.addAll(this.czsj.getView());
        values.addAll(this.bmsj.getView());
        values.addAll(this.myzt.getView());
        values.addAll(this.djzt.getView());
        values.addAll(this.gyxh.getView());
        values.addAll(this.anxh.getView());
        values.addAll(this.tklx.getView());
        return values;
    }

    public void onDestroy() {
        if(mysz!=null){
            mysz.onDestroy();
        }
        try {
            EventBus.getDefault().unregister(this);
        }catch (Exception e){

        }
    }

    /**
     * 050310000100000064000505DC002013888080B8F3 - 例子
     *
     * @param bytes
     */
    public void parseByte(byte[] bytes) {
        // 投口号转十进制
        int tkh = ByteUtil.hexStringToInt(ByteUtil.hexByteToString(bytes[0]));
        // 距离值(满溢数值)
        int jlz = ByteUtil.hexStringToInt(ByteUtil.hexBytesToString(new byte[]{bytes[5], bytes[6]}));
        // 距离限值(满溢限值)
        int jlxz = ByteUtil.hexStringToInt(ByteUtil.hexBytesToString(new byte[]{bytes[7], bytes[8]}));
        // 电机电流
        int djdl = ByteUtil.hexStringToInt(ByteUtil.hexBytesToString(new byte[]{bytes[9], bytes[10]}));
        // 电机限流
        int djxl = ByteUtil.hexStringToInt(ByteUtil.hexBytesToString(new byte[]{bytes[11], bytes[12]}));
        // 重量值
        int zlz = ByteUtil.hexStringToInt(ByteUtil.hexBytesToString(new byte[]{bytes[13], bytes[14]}));
        // 闭门时间
        int bmsj = ByteUtil.hexStringToInt(ByteUtil.hexBytesToString(new byte[]{bytes[15], bytes[16]}));
        // 状态标志
        String ztbz = ByteUtil.hexBytesToString(new byte[]{bytes[17], bytes[18]});
        // 投口类型
        String type = ByteUtil.hexByteToString(bytes[4]);

        // 如果打开了对应投口开关，才给这个投口赋值
        LinkedList<CustomTextView> views = getCustomTextViewListByTK(tkh);
        setData(views, jlz, jlxz, djdl, djxl, zlz, bmsj, ztbz, type);
    }

    /**
     * @param views
     * @param jlz   距离值(满溢数值)
     * @param jlxz  距离限值(满溢限值)
     * @param djdl  电机电流
     * @param djxl  电机限流
     * @param zlz   重量值
     * @param bmsj  闭门时间
     * @param ztbz  状态标志
     * @param type  投口类型
     */
    private void setData(LinkedList<CustomTextView> views,
                         int jlz,
                         int jlxz,
                         int djdl,
                         int djxl,
                         int zlz,
                         int bmsj,
                         String ztbz,
                         String type) {
        if(views==null){
            return;
        }
        if(views.get(0)==null){
            return;
        }
        // 状态标志转为二进制
        String sec = ByteUtil.String_0(ByteUtil.hexStringToBinary(ztbz), 16);
        int djzt = ByteUtil.binaryToInt("0" + sec.substring(1, 4));

        LOG.e(TAG, String.format("状态标志：%s", StringUtils.subStringToSpace(sec, 4)));
        LOG.e(TAG, String.format("电机状态值：%s", djzt));

        views.get(0).setText("" + jlz);
        views.get(1).setText("" + jlxz);
        views.get(2).setText("" + djdl);
        views.get(3).setText("" + djxl);
        views.get(4).setText("" + zlz);
        views.get(5).setText("" + bmsj);
        views.get(6).setText(sec.substring(0, 1).equals("0") ? "正常" : "满溢");
        views.get(7).setText(getDjzt(djzt));
        views.get(8).setText(sec.substring(4, 5).equals("0") ? "正常" : "触发");
        views.get(9).setText(sec.substring(5, 6).equals("0") ? "正常" : "触发");
        views.get(10).setText(getTklx(type));
    }

    /**
     * 根据投口地址(十进制)，获取TextView集合
     *
     * @param tkDz
     * @return
     */
    public LinkedList<CustomTextView> getCustomTextViewListByTK(int tkDz) {
        if (tkViewMap == null) {
            // 投口位置（纯数字）
            int tk = ByteUtil.hexStringToInt(ByteUtil.hexByteToString(SingletonSerl.byte_tk1));
            // 投口数量
            int tk_num = SingletonSerl.bytes_tk.length;
            tkViewMap = new HashMap<>();
            LinkedList<CustomTextView> list = getCustomTextViewList();
            for (int i = 0; i < list.size(); i++) {
                // ((当前位置+1)%投口数量)%投口位置 == 0 即对应 tk 字段的数组
                if (((((i + 1) % tk_num) % tk)) % tk == 0) {
                    LinkedList<CustomTextView> l = tkViewMap.get("" + tk) == null ? new LinkedList<>() : tkViewMap.get("" + tk);
                    l.add(list.get(i));
                    tkViewMap.put("" + tk, l);
                    tk++;
                    if (tk > tk_num) {
                        tk = 1;
                    }
                }
            }
        }
        return tkViewMap.get("" + tkDz);
    }
}
